package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.bean.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping("user/{userId}")
    @ResponseBody
    public ResponseVo<List<Cart>> queryCheckedCartsByUserId(@PathVariable("userId")Long userId){
        List<Cart> carts = cartService.queryCheckedCartsByUserId(userId);
        return ResponseVo.ok(carts);
    }

    @GetMapping("syncData")
    @ResponseBody
    public void syncData(){
        cartService.syncData();
    }


    /**
     * 新增购物车方法
     * 参数cart中只有浏览器传递的：skuId 和 count
     * @return
     */
    @GetMapping
    public String addCart(Cart cart){

        cartService.addCart(cart);
        return "redirect:http://cart.gmall.com/addCart.html?skuId=" + cart.getSkuId() + "&count=" + cart.getCount();
    }

    @GetMapping("addCart.html")
    public String queryCartBySkuId(Cart cart, Model model){
        BigDecimal count = cart.getCount();
        cart = cartService.queryCartBySkuId(cart.getSkuId());
        cart.setCount(count);
        model.addAttribute("cart", cart);
        return "addCart";
    }

    /**
     * 只要根据userKey 或者userId查询就可以了，不需要任何参数
     * @return
     */
    @GetMapping("cart.html")
    public String queryCarts(Model model){
        List<Cart> carts = cartService.queryCarts();
        model.addAttribute("carts", carts);
        return "cart";
    }

    @PostMapping("updateNum")
    @ResponseBody
    public ResponseVo updateNum(@RequestBody Cart cart){
        cartService.updateNum(cart);
        return ResponseVo.ok();
    }

    @PostMapping("updateStatus")
    @ResponseBody
    public ResponseVo updateStatus(@RequestBody Cart cart){
        cartService.updateStatus(cart);
        return ResponseVo.ok();
    }

    @PostMapping("deleteCart")
    @ResponseBody
    public ResponseVo deleteCart(@RequestParam("skuId") Long skuId){
        cartService.deleteCart(skuId);
        return ResponseVo.ok();
    }


//    @GetMapping("test")
//    @ResponseBody
//    public String test(){
//        System.out.println("========test===========" + LoginInterceptor.getUserInfo().toString());
//        return "hello test";
//    }
}
